package mysql

import (
	"furni-set/setrpc/setrpc"

	"gorm.io/gorm"
)

type Goods struct {
	gorm.Model
	Name    string  `gorm:"type:varchar(30);not null;commit:商品名称"`
	Price   float64 `gorm:"type:decimal(10,2);not null;commit:商品价格"`
	Stock   int64   `gorm:"type:int(11);not null;commit:'商品库存'"`
	Image   string  `gorm:"type:varchar(500);not null;commit:'商品图片'"`
	ClassId int64   `gorm:"type:int(11);not null;commit:'分类id'"`
}

func (g *Goods) GoodsAdd(db *gorm.DB) error {
	return db.Debug().Create(g).Error
}

func (g *Goods) FindGoods(db *gorm.DB, name string) error {
	return db.Debug().Where("name=?", name).First(g).Error
}

func GoodsList(db *gorm.DB, lists []*setrpc.GoodsList, in *setrpc.GoodsListRequest) []*setrpc.GoodsList {
	tx := db.Debug().Model(&Goods{}).Select("goods. id as goods_id, goods. name as goods_name, goods. price, goods. stock, goods. image, classes.name as class_name, goods. created_at").
		Joins("left join classes on classes.id = goods.class_id").Find(&lists)
	if in.GoodsName != "" {
		tx = tx.Where("goods.name like ?", "%"+in.GoodsName+"%")
	}
	if in.ClassName != "" {
		tx = tx.Where("classes.name  =? ", in.ClassName)
	}
	if in.EndPrice > 0 {
		tx = tx.Where("goods.price <=?", in.EndPrice)
	}
	if in.StartPrice > 0 {
		tx = tx.Where("goods.price >= ?", in.StartPrice)
	}
	if in.StartCreatedAt != "" {
		tx = tx.Where("goods.created_at>=?", in.StartCreatedAt)
	}
	if in.EndCreatedAt != "" {
		tx = tx.Where("goods.created_at <= ?", in.EndCreatedAt)
	}
	tx.Find(&lists)
	return lists

}
